package com.mbigger.synchronize;

/**
 * 方法抛异常后，会释放锁
 * <p>
 * 展示不抛出异常前和抛出异常后的对比，一旦抛出了异常，<br/>
 * 第二各线程会立即进入同步方法，意味着锁已经释放。
 * </p>
 *
 * @author mbigg
 *
 */
public class SynchronizedException9 implements Runnable {
    static SynchronizedException9 instance = new SynchronizedException9();

    public static void main(String[] args) {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        while (t1.isAlive() || t2.isAlive()) {
        }
        System.err.println("finished!");
    }

    public void run() {
        if (Thread.currentThread().getName().equals("Thread-0")) {
            method1();
        } else {
            method2();
        }
    }

    public static synchronized void method1() {
        System.err.println("我是静态加锁的方法1，我叫：" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
            throw new RuntimeException("同步方法异常测试");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        System.err.println("运行结束：" + Thread.currentThread().getName());
    }

    public static synchronized void method2() {
        System.err.println("我是静态加锁的方法2，我叫：" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.err.println("运行结束：" + Thread.currentThread().getName());
    }

}
